using System;
using System.Net;

namespace BuildBox.Core.Server.Adapters
{
    public interface IHttpListenerAdapter
    {
        void Start();
        void Stop();
        void AddPrefix(string uriPrefix);
        IAsyncResult BeginGetContext(AsyncCallback callback, object state);
        IHttpListenerContextAdapter EndGetContext(IAsyncResult results, IConfiguration configuration);
    }

    public class HttpListenerAdapter : IHttpListenerAdapter
    {
        private readonly HttpListener _listener;

        public HttpListenerAdapter()
        {
            _listener = new HttpListener();
        }

        public void Start()
        {
            _listener.Start();
        }

        public void Stop()
        {
            _listener.Stop();
        }

        public void AddPrefix(string uriPrefix)
        {
            _listener.Prefixes.Add(uriPrefix);
        }

        public IAsyncResult BeginGetContext(AsyncCallback callback, object state)
        {
            return _listener.BeginGetContext(callback, state);
        }

        public IHttpListenerContextAdapter EndGetContext(IAsyncResult results, IConfiguration configuration)
        {
            HttpListenerContext context = _listener.EndGetContext(results);
            return new HttpListenerContextAdapter(context, configuration);
        }
    }
}